package com.hisense.hiioc.hismartplate.config;

import com.hisense.hiioc.hismartplate.service.WeatherDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Auther:liaohongbing@hisense.com
 * @date:2019/5/7
 * @des 应用启动后执行的操作
 */


@Component
@Order(value = 1)
public class ApplicationBootTask implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(ApplicationBootTask.class);

    @Autowired
    WeatherDataService weatherService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        try{
            logger.info("weather data init");
            String weatherData = weatherService.getEnvironmentInfo().toJSONString();
            logger.info(weatherData);
            Message message = MessageBuilder.withBody(weatherData.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON).build();

            rabbitTemplate.convertAndSend("weather_data",message);
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Scheduled(cron = "0 0/20 * * * ?")
    public void weatherDataScheduledTask(){
//        logger.info("test  "+new Date());

        logger.info("weather data scheduler");
        String weatherData = weatherService.getEnvironmentInfo().toJSONString();
        logger.info(weatherData);
        Message message = MessageBuilder.withBody(weatherData.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON).build();

        rabbitTemplate.convertAndSend("weather_data",message);
    }

}
